package edu.ccut.saturn.manager.menu.core;

import java.util.ArrayList;
import java.util.List;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IMuneItemInfo;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnMenuManager;

public class MenuItemUp extends DefaultComponent {
	@Override
	public void execute(IParameterContext parameterContext) throws Exception {

		String id = (String) parameterContext.getParameterValue(0);
		String bundleName = (String) parameterContext.getParameterValue(1);
		String menuType = (String) parameterContext.getParameterValue(2);

		List<IMuneItemInfo> menuItemList = SaturnMenuManager.getInstance()
				.getAllRootMenuItemInfo();
		
		if (menuType == null) {
			menuType = "";
		}
		if (menuType.equals("child")) {
			List<IMuneItemInfo> menuItems = SaturnMenuManager.getInstance()
					.getAllMenuItemInfos();

			String parentId = "";
			for (IMuneItemInfo menuItem : menuItems) {
				if (menuItem.getId().equals(id)
						&& menuItem.getMenuInfo().getBundleSymbolicName()
								.equals(bundleName)) {

					parentId = menuItem.getParentId();
					break;
				}
			}
			if (!"".equals(parentId)) {
				menuItemList = SaturnMenuManager.getInstance()
						.getMenuItemsOfRootMenuItem(parentId);

			}
		}
		List<IMuneItemInfo> returnMenuItemList = new ArrayList<IMuneItemInfo>();
		if (menuItemList.size() > 0) {
			for (int i = 0; i < menuItemList.size(); i++) {
				IMuneItemInfo itemInfo = menuItemList.get(i);

				if (id.equals(itemInfo.getId())
						&& bundleName.equals(itemInfo.getMenuInfo()
								.getBundleSymbolicName()) && i > 0) {

					IMuneItemInfo itemInfoPre = menuItemList.get(i - 1);
					String itemInfoOrder = itemInfo.getOrder();
					itemInfo.setOrder(itemInfoPre.getOrder());
					itemInfoPre.setOrder(itemInfoOrder);
					returnMenuItemList.add(itemInfo);
					returnMenuItemList.add(itemInfoPre);
					break;
				}
			}
		}
		parameterContext.setParameter(3, returnMenuItemList);
	}
}